﻿using System.Collections.Generic;
using System.Threading;

namespace Fluffy.Archive.DragDropEngine
{
	internal class SyncQueue<T>
	{
		private readonly Queue<T> _data = new Queue<T>();
		private readonly Semaphore _semaphore = new Semaphore(0, int.MaxValue);

		private bool _isFinished;
		
		public void Enqueue(T item, bool isFinished)
		{
			lock (_data)
			{
				_data.Enqueue(item);
				_isFinished = isFinished;
			}

			_semaphore.Release();
		}

		public T Dequeue()
		{
			if (_isFinished && _data.Count == 0)
				return default(T);

			_semaphore.WaitOne();
			
			lock (_data)
			{
				return _data.Dequeue();
			}
		}
	}
}
